﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace YinLongTool.IO
{
    public class FileUtil
    {
        private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

        //FileStream类操作的是字节和字节数组，而Stream类操作的是字符数据
        private readonly FileStream _fileStream;
        public FileUtil(string path)
        {

            //if (File.Exists(_path))
            //{
            //    System.IO.FileStream f = System.IO.File.Create(_path);
            //    f.Close();
            //    f.Dispose();
            //}
            _fileStream = new FileStream(path, FileMode.Append);
        }
        public void WriteLog(Exception ex, EnumLogLevel enumLogLevel = EnumLogLevel.Debug)
        {
            string content =
                $"{enumLogLevel.ToString()}  {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)}"
                + Environment.NewLine +
        string.Format("错误信息：{1}{0}错误来源：{2}{0}堆栈信息：{0}{3}", Environment.NewLine, ex.Message, ex.Source, ex.StackTrace);
            byte[] data = System.Text.Encoding.Default.GetBytes(content);
            _lock.EnterWriteLock();
            _fileStream.Write(data, 0, data.Length);
            _fileStream.Flush();
            _lock.ExitWriteLock();
        }
        public void WriteContent(string content)
        {
            byte[] data = System.Text.Encoding.Default.GetBytes(content);
            _lock.EnterWriteLock();
            _fileStream.Write(data, 0, data.Length);
            _fileStream.Flush();
            _lock.ExitWriteLock();
        }
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">内容</param>
        public static void FileAdd(string Path, string strings)
        {
            StreamWriter sw = File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }

    }
    public enum EnumLogLevel
    {
        All,
        Debug,
        Info,
        Warn,
        Error
    }
}
